package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.model.mongo.VideoScore;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 监听器
 *   监听所有 log.viode的日志消息
 */
@Component
public class VideoListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.video.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.log.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.video"
            )
    )
    public void listener(String message) {
        System.out.println("获取评分的消息="+message);
        //1、解析消息，获取数据
        Map map = JSON.parseObject(message, Map.class);
        String type = map.get("type").toString();   //对动态的操作类型
        String videoId = map.get("busId").toString();
        String string = map.get("userId").toString();
        Long userId = Long.valueOf(string);
        //2、构造视频评分对象
        VideoScore vs = new VideoScore();
        vs.setUserId(userId);
        vs.setVideoId(new ObjectId(videoId));
        vs.setDate(System.currentTimeMillis());
        //评分
        Double score = getScore(type);
        vs.setScore(score);
        //3、存入到mongodb，推荐系统会自己动计算，并推荐数据
        mongoTemplate.save(vs);
    }

    private static Double getScore(String type) {
        //0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
        Double score = 0d;
        switch (type) {
            case "0301":
                score=2d;
                break;
            case "0302":
                score=5d;
                break;
            case "0303":
                score = -5d;
                break;
            case "0304":
                score = 10d;
                break;
            default:
                break;
        }
        return score;
    }
}
